<template>
  <BasicModal :width="1500" v-bind="$attrs" :title="getTitle"
    :canFullscreen="false" :centered="true" :destroyOnClose="true" :showCancelBtn="false" :showOkBtn="false"
    :bodyStyle="{height:'calc(100vh - 150px)', overflow:'hidden'}"
    @register="registerModal"
  >
    <!-- 查询区域 -->
    <div class="jeecg-basic-table jeecg-basic-table-form-container">
      <a-form @keyup.enter.native="searchQuery">
        <a-row :gutter="8" type="flex">

          <a-col flex="285px">
            <a-form-item label="日期" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ style: { width: '245px' } }">
              <a-date-picker
                v-model:value="queryParam.beginDate"
                :disabled-date="disabledStartDate"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 109px; padding: 4px;"
              /> ~
              <a-date-picker
                v-model:value="queryParam.endDate"
                :disabled-date="disabledEndDate"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 109px; padding: 4px;"
              />
            </a-form-item>
          </a-col>

          <a-col flex="118px">
            <a-form-item label="差异" :label-col="{ style: { width: '40px' } }" >
              <a-select v-model:value="queryParam.insider" placeholder="全部" :showArrow="false" :allowClear="true" :dropdown-match-select-width="90">
                <a-select-option value="1">有</a-select-option>
                <a-select-option value="0">无</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col flex="auto" style="float:right; width:90px; margin-right: 0px;">
            <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" color="success" @click="searchQuery" preIcon="ant-design:search">查询</a-button>
              <a-button type="primary" color="warning" @click="handleBankBalanceRealAnalyse" preIcon="ant-design:line-chart-outlined">分析</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域 -->
    
    <BasicTable @register="registerTable" 
      :onRowDbClick="handleDblclick" :onRowClick="handleClick" :rowClassName="rowClassName" :loading="loading"
    >
    </BasicTable>
  </BasicModal>

  <BankBalanceRealCheck @register="registerBankBalanceCheck"></BankBalanceRealCheck>
  <BankBalanceRealAnalyse @register="registerBankBalanceRealAnalyse"></BankBalanceRealAnalyse>
</template>

<script lang="ts" name="BankBalanceModal" setup>
  import {ref, toRaw, h, reactive} from 'vue';
  import {BasicModal, useModalInner, useModal} from '/@/components/Modal';
  import {BasicTable, BasicColumn} from '/@/components/Table';
  import {findBalanceRealList} from "/@/views/full/bank/types/bank.api";
  import {useListPage} from '/@/hooks/system/useListPage';
  import {filterObj} from '/@/utils/common/compUtils';
  import {render} from '/@/utils/common/renderUtils';
  import BankBalanceRealCheck from "/@/views/full/bank/modules/BankBalanceRealCheck.vue";
  import BankBalanceRealAnalyse from "/@/views/full/bank/modules/BankBalanceRealAnalyse.vue";
  import dayjs from 'dayjs';
import { select } from '/@/views/weixin/menu/menu.api';
  //----------定义变量 开始-------------------------------------------------------------
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  //标题
  const getTitle    = ref<any>('');
  const getTitleSub = ref<any>('');
  //定义查询表单，查询条件
  const queryParam  = reactive<any>({});

  //限制查询日期，开始日期不能大于结束日期
  function disabledStartDate(beginDate) {
    const endDate = queryParam.endDate;
    if (!beginDate || !endDate) {
      return false;
    }
    return beginDate.valueOf() > dayjs(endDate).valueOf()
  }

  function disabledEndDate(endDate) {
    const beginDate = queryParam.beginDate;
    if (!endDate || !beginDate) {
      return false;
    }
    return dayjs(beginDate).valueOf() > endDate.valueOf();
  }
  //----------定义变量 结束-------------------------------------------------------------

  //二、初始化数据 -----------------------------------------------------------
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    setModalProps({confirmLoading: false});
    let record = data?.record || {};

    // 判断操作是新增还是修改
    getTitle.value       = record?.title + " _ " + record?.djm + ' __ 银行余额：' + record.t0lslrje;
    getTitleSub.value    = record?.title + " _ " + record?.djm ;
    queryParam.bankId    = record?.bankId;
    queryParam.beginDate = ''; //dayjs().subtract(2, 'month').startOf('month').format('YYYY-MM-DD'),
    queryParam.endDate   = record?.endDate;
    queryParam.insider   = '1'; //无差异
    searchQuery();
  });
  //二、初始化数据 -----------------------------------------------------------

  //三、初始化 -- 列表组件 -----------------------------------------------------------
  const statusFmt = ({ text }: { text: any }) => {
    if (text && text !== '合计') {
      const color = text == '0' ? 'green' : text == '1' ? 'red' : 'green';
      const value = text == '0' ? '未审' : text == '1' ? '已审' : '未审';
      return render.renderTag(value, color);
    }
  };

  /**
   * 对账结果表格样式
   * @param text 
   * @param record 
   */
  const getCellStyle = ({ text, record }) => {
    let backgroundColor = '';
    if (record.lrce != '0.00') {
      backgroundColor = '#ffeeee'; // 负数为红色
    }

    return h('div', { style: { backgroundColor, margin: '-8px', padding: '8px'} }, text);
  }

  const setCellFooter = ({ text, record }) => {
    let backgroundColor = '', fontWeight = '';
    if (record.jzsj == '合计') {
      backgroundColor = '#eeeeff'; // 负数为红色
    }

    return h('div', { style: { backgroundColor, margin: '-8px', padding: '8px' } }, text);
  }

  // 订单列表 - 表头
  const columns: BasicColumn[] = [
    { title: '收支日期', align: 'center', dataIndex: 'jzsj', width: 90, className: 'text-' },
    { title: '银行收入', align: 'right', dataIndex: 'lssrje', width: 91, className: 'text-green-600' },
    { title: '银行支出', align: 'right', dataIndex: 'lszcje', width: 91, className: 'text-purple-600' },
    { title: '银行差额', align: 'right', dataIndex: 'lslrje', width: 91, className: 'text-rose-600', customRender: setCellFooter },
    { title: '系统收入', align: 'right', dataIndex: 'xtsrje', width: 91, className: 'text-green-600' },
    { title: '系统支出', align: 'right', dataIndex: 'xtzcje', width: 91, className: 'text-purple-600' },
    { title: '系统差额', align: 'right', dataIndex: 'xtlrje', width: 91, className: 'text-rose-600', customRender: setCellFooter },
    { title: '收入差额', align: 'right', dataIndex: 'srce', width: 91, className: 'text-green-600', customRender: getCellStyle },
    { title: '支出差额', align: 'right', dataIndex: 'zcce', width: 91, className: 'text-purple-600', customRender: getCellStyle },
    { title: '对账差额', align: 'right', dataIndex: 'lrce', width: 91, className: 'text-rose-600', customRender: getCellStyle },
    { title: '系统己审', align: 'right', dataIndex: 'xtyhje', width: 91, className: 'text-blue-600' },
    { title: '系统未审', align: 'right', dataIndex: 'xtwhje', width: 91, className: 'text-teal-600' },  
  ];

  // 列表页面公共参数、方法
  const loading = ref<boolean>(false);
  const { prefixCls, tableContext } = useListPage({
    designScope: 'bankBalance-page',
    tableProps: {
      rowKey: "jzsj",
      size: "small",
      api: findBalanceRealList,
      columns: columns,
      showTableSetting: false,
      showIndexColumn: true, //行号
      showActionColumn: false,
      useSearchForm: false,
      resizeHeightOffset: 40,
      showSummary: true,
      immediate: false, 
      summaryFunc: handleSummary,
      beforeFetch: (params) => Object.assign(params, filterObj(queryParam)),
      //summaryData: summaryData,
    }
  });

  //注册table数据
  const [registerTable, { reload, setProps, getRawDataSource, redoHeight }] = tableContext;

  //三、初始化 -- 列表组件 -----------------------------------------------------------

  //四、数据列表 事件-----------------------------------------------------------
  /**
   * 查询
   */
  function searchQuery() {
    let params = toRaw(filterObj(queryParam));
    setProps({ searchInfo: params });
    reload();
  }

  /**
   * 合计
   */
  function handleSummary(tableData: Recordable[]) {
    const res = getRawDataSource()
    redoHeight();
    if (res) {
      return getRawDataSource().summary;
    } else {
      return [];
    }
  }

  //单击行
  let selectRows = reactive<any>({ id: '', lsid: '', xtid: '' });
  function handleClick(record) {
    selectRows.id   = record.id;
    selectRows.lsid = record.lsid;
    selectRows.xtid = record.xtid;
  }

  //双击行
  function handleDblclick(record) {
    handleEdit(record);
  }

  function rowClassName(record, index) {
    return record.id === selectRows.id ? 'row-selected' : '';
  }

  //四、数据列表 事件-----------------------------------------------------------

  //五、对账组件------------------------
  const [registerBankBalanceCheck, {openModal: openBankBalanceCheck}] = useModal();
  /**
   * 对账明细
   */
  function handleEdit(record) {
    let params = {
      djm: record.djm,
      beginDate: record.id,
      bankId: queryParam.bankId,
      title: getTitleSub.value
    }

    openBankBalanceCheck(true, { record: {...params}, isUpdate: false });
  }

  const [registerBankBalanceRealAnalyse, {openModal: openBankBalanceRealAnalyse}] = useModal();
  /**
   * 系统流水
   */
  function handleBankBalanceRealAnalyse() {
    if (!selectRows.id) {
      //$message.error('请选择一条记录');
      return;
    }
    let params = {
      beginDate: selectRows.id,
      bankId: queryParam.bankId,
      title: getTitleSub.value + " __ 收支日期 " + selectRows.id
    };
    openBankBalanceRealAnalyse(true, { record: {...params}, isUpdate: true });
  }
  //五、对账组件------------------------
</script>

<style lang="less" scoped>
  button {
    margin-right: 10px;
  }
</style>